<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        img {
            vertical-align: top;
        }

        .ad-wrapper {
            width: 300px;
            /* height: 400px; */
            background-color: grey;
            position: fixed;
            right: 5px;
            bottom: 5px;
            display: none;
        }

        .ad-header {
            font-size: 14px;
            line-height: 30px;
            position: relative;
        }

        .ad-header .ad-close {
            padding: 0 5px;
            background-color: red;
            color: #fff;
            position: absolute;
            right: 0;
            top: 0;
        }

        .ad-content img {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="ad-wrapper">
        <div class="ad-header">
            <div class="ad-title">距离广告关闭还有10秒</div>
            <div class="ad-close">x</div>
        </div>
        <div class="ad-content">
            <img src="../images/bzsc-dgbhz-300-250-7-5.gif" alt="">
        </div>
    </div>
</body>
<script>
    // 小广告
    // 1. 页面加载完毕 等待5s 小广告显示
    // 2. 倒计时10s后关闭小广告
    // 3. 重复1-2
    // 4. 点击关闭按钮 => 清除小广告  => 重复 1 2 3

    var adWrapper = document.getElementsByClassName("ad-wrapper")[0];
    var adTitle = document.getElementsByClassName("ad-title")[0];
    var adClose = document.getElementsByClassName("ad-close")[0];

    var t1 = null; //记录延时器的编号
    var t2 = null;
    adverLoop();

    // // 延时器从开始 到 第一次执行函数需要 5s (5s内可以清除延时器 => 隐藏), 5s后计时器开启, 清除延时器,并不会影响计时器 => 计时器倒计时结束 -> 递归调用

    // 解决方法: 点击关闭时,同时清除计时器和延时器
    adClose.onclick = function () {
        adWrapper.style.display = "none";
        clearTimeout(t1);
        clearInterval(t2);

        adverLoop();
    }


    function adverLoop(delay) {
        delay = delay == undefined ? 5000 : delay;

        clearTimeout(t1);
        t1 = setTimeout(function () {
            adWrapper.style.display = "block";

            var sum = 10;
            adTitle.innerText = `距离广告关闭还有${sum}秒`;
            t2 = setInterval(function () {
                sum--;
                adTitle.innerText = `距离广告关闭还有${sum}秒`;
                if (sum <= 0) {
                    clearInterval(t2);
                    adWrapper.style.display = "none";

                    adverLoop(delay);
                }
            }, 1000);

        }, delay);
    }




</script>

</html>